from tkinter import *
from PIL import Image
from PIL import ImageTk
import http.client
import urllib.parse
import re

class MainForm(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.title("爱漫画" )
        self.loadForm()
        

    def close(self):
        self.destroy()

    def openFile(self):
        self.status['text'] = '打开。。'
        
    def loadForm(self):
         
        topFrame = Frame(height=100,bg='red') 
        topFrame.pack(side=TOP, fill=X)
        
        bottomFrame = Frame(height=100)  
        bottomFrame.pack(side=BOTTOM, fill=X)
        
        self.quit = Button (topFrame, text="Quit", command=self.close )
        self.quit.pack(side=RIGHT, fill=Y, pady=1,padx=1)
        self.open = Button (topFrame, text="Open", command=self.openFile )
        self.open.pack(side=LEFT, fill=Y, pady=1,padx=1)

        self.status = Label(bottomFrame,text='测试中。。',compound=BOTTOM)  
        self.status.pack(side=LEFT, fill=X, pady=1,padx=1)
        '''
        self.imgs = PhotoImage(file='man.gif') 
        canvas = Canvas(self,  width = 500,   height = 600)
        #canvas.create_image(200,50,image = self.img, state=NORMAL) 
        'canvas.create_text(302,77,       # 使用create_text方法在坐标（302，77）处绘制文字
           text = 'Use Canvas'      # 所绘制文字的内容
           ,fill = 'gray')       # 所绘制文字的颜色为灰色
        canvas.create_text(300,75,
           text = 'Use Canvas',
           fill = 'blue')
        
        canvas.pack() 

        imgLabel = Label(self,image=self.imgs) 
        imgLabel.pack() '''
        self.btnHuoYing = Button (topFrame, text="火影忍者", command=self.btnHuoYing_click )
        self.btnHuoYing.pack(side=LEFT, fill=Y, pady=1,padx=1)

        self.btnLastChapter = Button (topFrame, text="最后一话", command=self.btnLastChapter_click )
        self.btnLastChapter.pack(side=LEFT, fill=Y, pady=1,padx=1)

        self.txtContent = Text (self)
        self.txtContent.pack()
        
    #下载火影忍者集数    
    def btnHuoYing_click(self):
        self.chapterList=[]
        conn = http.client.HTTPConnection('www.imanhua.com')
        conn.request("GET", "/comic/54/")
        r1 = conn.getresponse()
        data1 = r1.read().decode('gb2312')
        #print(data1)
        matches=re.findall('''<a[^>]{0,100}href=[^/>]{0,1}([^\s'>"]{10,50})[^/>]{0,1}[^>]{0,100}>[^\d<]{0,20}火影忍者(\d+)(话)(正式版){0,1}(<em></em>){0,1}</a>''',data1,re.IGNORECASE)
        for m in matches:
            newChapter = ChapterView()
            newChapter.SourceUrl=m[0]
            newChapter.Number=m[1]
            
            self.chapterList.append(newChapter)
            self.txtContent.insert(INSERT, m[0] + "\t" + m[1] )
            self.txtContent.insert(INSERT, "\n") 
        
        
    
    #下载火影最新一章节
    def btnLastChapter_click(self):
        lastChapter = self.chapterList[1]
        print(lastChapter.Number + ":" + lastChapter.SourceUrl )
        conn = http.client.HTTPConnection('www.imanhua.com')
        conn.request("GET", lastChapter.SourceUrl)
        r1 = conn.getresponse()
        data1 = r1.read().decode('gb2312')
        print(data1)
        print('开始匹配脚本')
        matches=re.findall('''<script[^>]{0,50}>var pVars[^<]{0,2000}</script>''',data1,re.IGNORECASE)
        s = matches[0]
        print(s)
        print('开始匹配图片名称')
        matches=re.findall('''\|([^_\|0-9]{1,10}_)([^_\|]{1,5})(_[^_\|]{1,10}){0,1}\|''',s,re.IGNORECASE)
        #print(matches)
        for m in matches:
            print(m)
        
    def show(self): 
        self.minsize(600, 400)
        self.mainloop()

class ChapterView:
    def __init__(self):
        self.ChapterID=0
        self.SourceUrl = ''
        self.Number = 0

def startProgram():
    mf = MainForm()
    mf.show()

if __name__ == "__main__":
    print("start")
    startProgram()
